var bord;
var IdRobot=-1;
var IdRobotPrec=-1;
var compteARebourd=60000;
var seconde = 0;
//les propositions se mettent dans ce tableau
var propositions = [];
var selectedRobot;
var nombreOperations = 0;

var red = { id: "", img: "", color: "", line: 0, column: 0};
var yellow = { id: "" ,img: "", color: "", line: 0, column: 0};
var blue = { id: "", img: "", color: "", line: 0, column: 0};
var green = { id: "", img: "", color: "", line: 0, column: 0};
var idGauche,idDroite,idBas,idHaut;
var Robots = new Array(blue, red, green, yellow);
var isRobotSelected=false;
var yellow="#5C5208";
var blue="#0b20bb";
var green="#3ba109";
var red="#f01818";
//structure d'un robot


//partie de l'affichage
//construit la table est met les evenement a gerer sur les cellule
function dessinerPlateauDeJeu(bordDuJeu) {
	var body = document.getElementById('myBoard');
	var tbl = document.createElement('table');
	var tbdy = document.createElement('tbody');
	for (var i = 0; i < 16; i++) {
		var tr = document.createElement('tr');
		for (var j = 0; j < 16; j++) {
			var td = document.createElement('td');
			td.setAttribute("id", i + "_" + j);
			if (bordDuJeu.board[i][j].g){
				td.style.borderLeft = "thick solid #000000";
			}
			if (bordDuJeu.board[i][j].d){
				td.style.borderRight = "thick solid #000000";
			}
			if (bordDuJeu.board[i][j].h){
				td.style.borderTop = "thick solid #000000";
			}
			if (bordDuJeu.board[i][j].b){
				td.style.borderBottom = "thick solid #000000";
			}
			td.appendChild(document.createTextNode(""));
			tr.appendChild(td);
			
		}
		tbdy.appendChild(tr);
	}
	tbl.appendChild(tbdy);
	body.appendChild(tbl);
	//initiliser les robot
	initialiserRobots(bordDuJeu);
	//dessiner la cible
	dessinerCible(bordDuJeu);
	document.getElementById('selectedRobot').innerHTML ="<span class='important' id='titre'>Robot selectionné :</span> aucun";


	//Cette fonction permet de gérer les évenements de type Swipe sur les surfaces tactiles
	document.addEventListener('touchstart', handleTouchStart, false);        
	document.addEventListener('touchmove', handleTouchMove, false);

	var xDown = null;                                                        
	var yDown = null;                                                        

	function handleTouchStart(evt) {                                         
	    xDown = evt.touches[0].clientX;                                      
	    yDown = evt.touches[0].clientY;                                      
	};                                                

	function handleTouchMove(evt) {
	    if ( ! xDown || ! yDown ) {
	        return;
	    }

	    var xUp = evt.touches[0].clientX;                                    
	    var yUp = evt.touches[0].clientY;

	    var xDiff = xDown - xUp;
	    var yDiff = yDown - yUp;

	    if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {/*most significant*/
	        if ( xDiff > 0 ) {
	            /* left swipe */ 
	            idGauche=mouvementVersLaGauche(Robots[IdRobot].line,Robots[IdRobot].column);
				if(Robots[IdRobot].id != idGauche) {
					amenerRobot(idGauche);
				}
	        } else {
	            /* right swipe */
	            idDroite=mouvementVersLaDroite(Robots[IdRobot].line,Robots[IdRobot].column);
				if(Robots[IdRobot].id != idDroite) {
					amenerRobot(idDroite);
				}
	        }                       
	    } else {
	        if ( yDiff > 0 ) {
	            /* up swipe */ 
	            idHaut=mouvementVersLeHaut(Robots[IdRobot].line,Robots[IdRobot].column);
				if(Robots[IdRobot].id != idHaut) {
					amenerRobot(idHaut);
				}
	        } else { 
	            /* down swipe */
	            idBas=mouvementVersLeBas(Robots[IdRobot].line,Robots[IdRobot].column);
				if(Robots[IdRobot].id != idBas) {
					amenerRobot(idBas);
				}
	        }                                                                 
	    }
	    /* reset values */
	    xDown = null;
	    yDown = null;                                             
	};
	
	//On ajoute le listener sur les claviers
	document.addEventListener("keydown", keyDownEvent, false);
}


//Fonction appelé lorsqu'un touche de clavier est pressé
function keyDownEvent(e) {
	var keyCode = e.keyCode;
	
	//Désactive le scroll par défaut lorsqu'on presse les flèches directionnelles
	if([32, 37, 38, 39, 40].indexOf(keyCode) > -1) {
		e.preventDefault();
	}

	if(isRobotSelected == true) { // <--- sécuriser le déplacement ici pour éviter les déplacements dans les murs

		console.log("Key pressed ",keyCode);
	    switch(keyCode) {
			case 37: //Gauche
				idGauche=mouvementVersLaGauche(Robots[IdRobot].line,Robots[IdRobot].column);
				if(Robots[IdRobot].id != idGauche) {
					amenerRobot(idGauche);
				}
				break;
			case 38: //Haut

				idHaut=mouvementVersLeHaut(Robots[IdRobot].line,Robots[IdRobot].column);
				if(Robots[IdRobot].id != idHaut) {
					amenerRobot(idHaut);
				}
				
				break;
			case 39: //Droite
				idDroite=mouvementVersLaDroite(Robots[IdRobot].line,Robots[IdRobot].column);
				if(Robots[IdRobot].id != idDroite) {
					amenerRobot(idDroite);
				}
				break;
			case 40: //Bas
				idBas=mouvementVersLeBas(Robots[IdRobot].line,Robots[IdRobot].column);
				if(Robots[IdRobot].id != idBas) {
					amenerRobot(idBas);
				}
				break;
			case 66: //B Blue 
				IdRobot = 0;
				afficherProposition(IdRobot);
				break;
			case 71: //G Green 
				IdRobot = 2;
				afficherProposition(IdRobot);
				break;
			case 86: //V Vert
				IdRobot = 2;
				afficherProposition(IdRobot);
				break;
			case 82: //R Red 
				IdRobot = 1;
				afficherProposition(IdRobot);
				break;
			case 89: //Y Yellow
				IdRobot = 3;
				afficherProposition(IdRobot);
				break;
			case 74: //J Jaune
				IdRobot = 3;
				afficherProposition(IdRobot);
				break;
			default:
				break;
		}
	}
}

//on place les robots avec leurs attribut drag et onclick qui vas contenir le fait de montrer les propositions
function initialiserRobots(bord) {
	for (var i = 0; i < 4; i++) {
		Robots[i].line = bord.robots[i].line;
		Robots[i].column = bord.robots[i].column;
		Robots[i].color = bord.robots[i].color;
		Robots[i].id = Robots[i].line + "_" + Robots[i].column;
		Robots[i].content = "<img class='robot' id=\"" + Robots[i].id + "\" src='style/img/" + Robots[i].color + "_robot.png' draggable='true'   height='26px' width='22px'  onclick=\"afficherProposition('"+i+"');\" />";
		Robots[i].alive = "YES";
	}
	for (var i = 0; i < 4; i++) {
	document.getElementById(Robots[i].line + "_" + Robots[i].column)
		 document.getElementById(Robots[i].line + "_" + Robots[i].column).innerHTML = Robots[i].content;
	}
}

//on place la cible selon ca couleur on choisi l'image
function dessinerCible(bord) {
	if(bord.target.t == "green")
		document.getElementById(bord.target.l + "_" + bord.target.c).innerHTML = "<img id='target' src='style/img/green_target.png'  width='26' height='26'/>";
	else if(bord.target.t == "red")
		document.getElementById(bord.target.l + "_" + bord.target.c).innerHTML = "<img id=\"target\" src='style/img/red_target.png'  width='26' height='26'/>";
	if(bord.target.t == "blue")
		document.getElementById(bord.target.l + "_" + bord.target.c).innerHTML = "<img id=\"target\" src='style/img/blue_target.png'  width='26' height='26'/>";
	if(bord.target.t == "yellow")
		document.getElementById(bord.target.l + "_" + bord.target.c).innerHTML = "<img  id=\"target\" src='style/img/yellow_target.png'  width='26' height='26'/>";
}

//place les robots apres un deplacement
function placerRobot() {
	 for (var i = 0; i < 4; i++) {
		 document.getElementById(Robots[i].line + "_" + Robots[i].column).innerHTML = Robots[i].content;
	}
}

//affichage des position de deplacement possible
function afficherProposition(IdRob){

IdRobotPrec=IdRobot;
IdRobot=IdRob;
isRobotSelected=true;
selectedRobot = Robots[IdRobot];

eventTouch = document.getElementById(Robots[IdRobot].id);
console.log("Robot : ",eventTouch);
propositions.push({command: 'select', robot: selectedRobot.color});
propositionSelection(propositions);
document.getElementById('selectedRobot').innerHTML ="<span class='important' id='titre'>Robot selectionné :</span> <img   align='center' src='style/img/" +Robots[IdRobot].color + "_robot.png' />";

var propRobots=document.getElementsByClassName('robotprop');
		var count=propRobots.length;
		for(var i=0;i<count;i++) 
		{
		propRobots[0].remove();
		}
		
		var carreRobots=document.getElementsByClassName('robotcarre');
		count=carreRobots.length;
		for(var i=0;i<count;i++) 
		{
		carreRobots[0].remove();
		}

		var pathRobots=document.getElementsByClassName('paths');
		 count=pathRobots.length;
		for(var i=0;i<count;i++) 
		{
		pathRobots[0].setAttribute("class","");
		}
		  idDroite=mouvementVersLaDroite(Robots[IdRobot].line,Robots[IdRobot].column);
		  idGauche=mouvementVersLaGauche(Robots[IdRobot].line,Robots[IdRobot].column);
		  idBas=mouvementVersLeBas(Robots[IdRobot].line,Robots[IdRobot].column);
		  idHaut=mouvementVersLeHaut(Robots[IdRobot].line,Robots[IdRobot].column);
		if(idDroite!=Robots[IdRobot].id) {
			document.getElementById(idDroite).innerHTML = "<img class=\"robotprop\" id=\"" + Robots[IdRobot].id+ "\" src='style/img/" +Robots[IdRobot].color + "_robot.png' height='26px' width='22px' onclick=\"amenerRobot('"+idDroite+"');\"/>";
				for (var i = (Robots[IdRobot].column+1); i < 16; i++) {
				if (bord.board[Robots[IdRobot].line][i].d) {
					break;
				}
				else {
					if (bord.board[Robots[IdRobot].line][i + 1].g) {
						break;
					}
					else if (robotDansLaPosition(Robots[IdRobot].line, (i + 1))) {
						break;
					}
				}
				document.getElementById(Robots[IdRobot].line + "_" + (i)).innerHTML = "<img class=\"robotcarre\" id=\"" + Robots[IdRobot].id+ "\" src='style/img/" +Robots[IdRobot].color + "_arrow_right.png' height='18px' width='18px' />";
			}
		}
		if(idGauche!=Robots[IdRobot].id) {
			document.getElementById(idGauche).innerHTML = "<img class=\"robotprop\" id=\"" + Robots[IdRobot].id+ "\" src='style/img/" +Robots[IdRobot].color + "_robot.png' height='26px' width='22px' onclick=\"amenerRobot('"+idGauche+"');\"/>";
			for (var i = (Robots[IdRobot].column-1); i >=0; i--) {
				if (bord.board[Robots[IdRobot].line][i].g) {
					break;
				}
				else {
					if (bord.board[Robots[IdRobot].line][i - 1].d) {
						break;
					}
					else if (robotDansLaPosition(Robots[IdRobot].line, (i - 1))) {
						break;
					}
				}
				document.getElementById(Robots[IdRobot].line + "_" + (i)).innerHTML = "<img class=\"robotcarre\" id=\"" + Robots[IdRobot].id+ "\" src='style/img/" +Robots[IdRobot].color + "_arrow_left.png' height='18px' width='18px' />";
			}
		}
		if(idBas!=Robots[IdRobot].id) {
			document.getElementById(idBas).innerHTML = "<img class=\"robotprop\" id=\"" + Robots[IdRobot].id+ "\" src='style/img/" +Robots[IdRobot].color + "_robot.png' height='26px' width='22px' onclick=\"amenerRobot('"+idBas+"');\"/>";
			for (var i = (Robots[IdRobot].line+1); i <16; i++) {
				if (bord.board[i][Robots[IdRobot].column].b) {
					break;
				}
				else {
					if (bord.board[i + 1][Robots[IdRobot].column].h) {
						break;
					}
					else if (robotDansLaPosition((i+1), Robots[IdRobot].column)) {
						break;
					}
				}
				document.getElementById((i) + "_" + Robots[IdRobot].column).innerHTML = "<img class=\"robotcarre\" id=\"" + Robots[IdRobot].id+ "\" src='style/img/" +Robots[IdRobot].color + "_arrow_down.png' height='18px' width='18px' />";
			}
		}
		if(idHaut!=Robots[IdRobot].id) {
			document.getElementById(idHaut).innerHTML = "<img class=\"robotprop\" id=\"" + Robots[IdRobot].id+ "\" src='style/img/" +Robots[IdRobot].color + "_robot.png' height='26px' width='22px' onclick=\"amenerRobot('"+idHaut+"');\"/>";
			for (var i = (Robots[IdRobot].line-1); i >=0; i--) {
				if (bord.board[i][Robots[IdRobot].column].h) {
					break;
				}
				else {
					if (bord.board[i - 1][Robots[IdRobot].column].b) {
						break;
					}
					else if (robotDansLaPosition((i-1), Robots[IdRobot].column)) {
						break;
					}
				}
				document.getElementById((i) + "_" + Robots[IdRobot].column).innerHTML = "<img class=\"robotcarre\" id=\"" + Robots[IdRobot].id+ "\" src='style/img/" +Robots[IdRobot].color + "_arrow_top.png' height='18px' width='18px' />";
			}
		}

}


//afficher les propositions sans envoyer la selection au serveur
function afficherPropositionSansSelection(IdRob){
IdRobotPrec=IdRobot;
IdRobot=IdRob;
isRobotSelected=true;
selectedRobot = Robots[IdRobot];
document.getElementById('selectedRobot').innerHTML ="<span class='important' id='titre'>Robot selectionné : </span> <img   align='center' src='style/img/" +Robots[IdRobot].color + "_robot.png' />";

var propRobots=document.getElementsByClassName('robotprop');
		var count=propRobots.length;
		for(var i=0;i<count;i++) 
		{
		propRobots[0].remove();
		}
		
		var carreRobots=document.getElementsByClassName('robotcarre');
		count=carreRobots.length;
		for(var i=0;i<count;i++) 
		{
		carreRobots[0].remove();
		}

		var pathRobots=document.getElementsByClassName('paths');
		 count=pathRobots.length;
		for(var i=0;i<count;i++) 
		{
		pathRobots[0].setAttribute("class","");
		}
		  idDroite=mouvementVersLaDroite(Robots[IdRobot].line,Robots[IdRobot].column);
		  idGauche=mouvementVersLaGauche(Robots[IdRobot].line,Robots[IdRobot].column);
		  idBas=mouvementVersLeBas(Robots[IdRobot].line,Robots[IdRobot].column);
		  idHaut=mouvementVersLeHaut(Robots[IdRobot].line,Robots[IdRobot].column);
		if(idDroite!=Robots[IdRobot].id) {
			document.getElementById(idDroite).innerHTML = "<img class=\"robotprop\" id=\"" + Robots[IdRobot].id+ "\" src='style/img/" +Robots[IdRobot].color + "_robot.png' height='26px' width='22px' onclick=\"amenerRobot('"+idDroite+"');\"/>";
				for (var i = (Robots[IdRobot].column+1); i < 16; i++) {
				if (bord.board[Robots[IdRobot].line][i].d) {
					break;
				}
				else {
					if (bord.board[Robots[IdRobot].line][i + 1].g) {
						break;
					}
					else if (robotDansLaPosition(Robots[IdRobot].line, (i + 1))) {
						break;
					}
				}
				document.getElementById(Robots[IdRobot].line + "_" + (i)).innerHTML = "<img class=\"robotcarre\" id=\"" + Robots[IdRobot].id+ "\" src='style/img/" +Robots[IdRobot].color + "_arrow_right.png' height='18px' width='18px' />";
			}
		}
		if(idGauche!=Robots[IdRobot].id) {
			document.getElementById(idGauche).innerHTML = "<img class=\"robotprop\" id=\"" + Robots[IdRobot].id+ "\" src='style/img/" +Robots[IdRobot].color + "_robot.png' height='26px' width='22px' onclick=\"amenerRobot('"+idGauche+"');\"/>";
			for (var i = (Robots[IdRobot].column-1); i >=0; i--) {
				if (bord.board[Robots[IdRobot].line][i].g) {
					break;
				}
				else {
					if (bord.board[Robots[IdRobot].line][i - 1].d) {
						break;
					}
					else if (robotDansLaPosition(Robots[IdRobot].line, (i - 1))) {
						break;
					}
				}
				document.getElementById(Robots[IdRobot].line + "_" + (i)).innerHTML = "<img class=\"robotcarre\" id=\"" + Robots[IdRobot].id+ "\" src='style/img/" +Robots[IdRobot].color + "_arrow_left.png' height='18px' width='18px' />";
			}
		}
		if(idBas!=Robots[IdRobot].id) {
			document.getElementById(idBas).innerHTML = "<img class=\"robotprop\" id=\"" + Robots[IdRobot].id+ "\" src='style/img/" +Robots[IdRobot].color + "_robot.png' height='26px' width='22px' onclick=\"amenerRobot('"+idBas+"');\"/>";
			for (var i = (Robots[IdRobot].line+1); i <16; i++) {
				if (bord.board[i][Robots[IdRobot].column].b) {
					break;
				}
				else {
					if (bord.board[i + 1][Robots[IdRobot].column].h) {
						break;
					}
					else if (robotDansLaPosition((i+1), Robots[IdRobot].column)) {
						break;
					}
				}
				document.getElementById((i) + "_" + Robots[IdRobot].column).innerHTML = "<img class=\"robotcarre\" id=\"" + Robots[IdRobot].id+ "\" src='style/img/" +Robots[IdRobot].color + "_arrow_down.png' height='18px' width='18px' />";
			}
		}
		if(idHaut!=Robots[IdRobot].id) {
			document.getElementById(idHaut).innerHTML = "<img class=\"robotprop\" id=\"" + Robots[IdRobot].id+ "\" src='style/img/" +Robots[IdRobot].color + "_robot.png' height='26px' width='22px' onclick=\"amenerRobot('"+idHaut+"');\"/>";
			for (var i = (Robots[IdRobot].line-1); i >=0; i--) {
				if (bord.board[i][Robots[IdRobot].column].h) {
					break;
				}
				else {
					if (bord.board[i - 1][Robots[IdRobot].column].b) {
						break;
					}
					else if (robotDansLaPosition((i-1), Robots[IdRobot].column)) {
						break;
					}
				}
				document.getElementById((i) + "_" + Robots[IdRobot].column).innerHTML = "<img class=\"robotcarre\" id=\"" + Robots[IdRobot].id+ "\" src='style/img/" +Robots[IdRobot].color + "_arrow_top.png' height='18px' width='18px' />";
			}
		}

}

//partie qui de controle et logique du jeu, reccuperation avec xmlhttprequest, et envoi avec xmlhttprequest

//fonciton de getion des requete xmlhttprequest
var XHR = function(method, ad, params) {
	var xhr = new XMLHttpRequest();
	xhr.onload = params.onload || null;
	xhr.open(method, ad);
	if (method == 'POST') {
		xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	}
	var variables = params.variables || null
			, str = '';
	for (var i in variables) {
		str += i + '=' + encodeURIComponent(variables[i]) + '&';
	}
	xhr.send(str);
}

//gestion des element envoyé par socket io
//liste des participants
// fin de la parite
//compte a rebours final apres qu'une solution est ete trouver
//solution proposé
function init() {
// Connect to the SocketIO server to retrieve ongoing games.
	socket = io.connect();
	socket.on('participants', function(data) {
		var ul = document.getElementById('players');
		ul.innerHTML = '';
		var player = document.getElementById('player').innerHTML;
		for (p in data.participants) {
			var li = document.createElement('li');
			li.setAttribute("class","buzz");
			var player = document.getElementById('player').innerHTML;
			if (data.participants[p] == player)
			{
				li.setAttribute("id", "current");
			}
			ul.appendChild(li);
			li.appendChild(document.createTextNode(data.participants[p]));
		}


	});

	socket.on('FinalCountDown', function(data) {
		var ms = data.FinalCountDown;
		FinalCounter = document.getElementById('FinalCounter').style.display = 'block';
		var iv = setInterval(function() {
			ms -= 1000;
			compteARebourd=ms;
			if (ms <= 0) {
				clearInterval(iv);
				document.getElementById('temps').innerHTML = 'Temps écoulé !';
			} else {
				document.getElementById('temps').innerHTML = 'Il vous reste :   '+parseInt(ms / 1000) + 's';
			}
		}, 1000);
		FinalCounter.innerHTML = 'Dépéchez vous il ne reste que' + ms + ' sec';
	});

	socket.on('solutions', function(data) {

		//alert("une solution a été trouvée par '" + data.solutions[0].player + "' en " + data.solutions[0].proposition.length + " opérations");
		var winner = document.getElementById('winner');
		winner.innerHTML = '<span>  ' + data.solutions[0].player + ' a trouvé une solution en ' + data.solutions[0].proposition.length + ' opérations</span>';
		solutions=data.solutions;
	});

	socket.on('TerminateGame', function(data) {
		arretTempsDeJeu();
		var win=0;
		var i=0
		for(i=0;i<solutions.length;i++)
			{
			if(solutions[i].proposition.length<solutions[win].proposition.length) win = i;
			}
				var winner = document.getElementById('winner');
				winner.innerHTML = '<span>  ' + solutions[win].player + ' a gagné la partie en ' + solutions[win].proposition.length + ' opérations</span>';
				alert(solutions[win].player + ' a gagné la partie en ' + solutions[win].proposition.length + ' opérations');
		

	});

	socket.emit('identification', {login: document.getElementById('login').value
				, idGame: document.getElementById('idGame').value}
	);
}

//reccuperer le plateau de jeu et le dessiner
function commencerJeu() {
	gameName = document.getElementById('idGame').value;
	playerName = document.getElementById('login').value;
	XHR('GET', "/" + document.getElementById('idGame').value + "", {onload: function() {
			bord = JSON.parse(this.responseText);
			dessinerPlateauDeJeu(bord);
		}
	});
}

function rafrechirCouleurBordure() {
	for (var i = 0; i < 16; i++) {
		for (var j = 0; j < 16; j++) {
			document.getElementById(i + "_" + j).style.backgroundColor = '';
		}
	}
}

//on reinitialise l'affichage des cellule
function initBordure() {
	for (var i = 0; i < 16; i++) {
		for (var j = 0; j < 16; j++) {
			document.getElementById(i + "_" + j).innerHTML = "";
		}
	}
}

//gerer le temps
function demarrerTempsDeJeu() {
	var labelMinute = document.getElementById("minutes");
	var labelSeconde = document.getElementById("seconds");
	setInterval(setTime, 1000);

	function setTime()
	{
		if (seconde < 600000) {
			++seconde;
			labelSeconde.innerHTML = bloc(seconde % 60);
			labelMinute.innerHTML = bloc(parseInt(seconde / 60));
		}
	}
	function bloc(val)
	{
		 var valString = val + "";
		if (valString.length < 2)
		{
			return "0" + valString;
		}
		else
		{
			return valString;
		}
	}
}

//arreter le temps
function arretTempsDeJeu() {
	seconde = 600000;
}

//ramener le robot sur la case en envoyant la proposition du mouvement au serveur, fonciton dans onclick sur une case qui est une case de proposition
function amenerRobot(id)
{
//expression reguliére pour reccuperer le num de la ligne et celui de la colonne
			var Ligne = id.substring(0,id.indexOf("_",0))
			var Colonne = id.substring((id.indexOf("_",0)+1),id.length)
			propositions.push({command: 'move', line: parseInt(Ligne), column: parseInt(Colonne)});
			//envoi de la proposition de mouvement
			propositionMouvement(propositions);
			
}

//change la position du robot
function majPositionRobot(lignePrec, colonnePrec, ligneNew, colonneNew) {

	for (var i = 0; i < 4; i++) {
		if ((Robots[i].line == lignePrec) && (Robots[i].column == colonnePrec)) {
			Robots[i].line = ligneNew;
			Robots[i].column = colonneNew;
			Robots[i].id = ligneNew + "_" + colonneNew;
			Robots[i].content = "<img class='robot' id=\"" + Robots[i].id + "\" src='style/img/" + Robots[i].color + "_robot.png' draggable='true' height='26px' width='22px' onclick=\"afficherProposition('"+i+"');\" />";

		}
	}
}

//envoi d'une propostiion de selection au serveur avec Xmlhttprequest
function propositionSelection(proposition) {
	var answer;
	var propXHR = XHR('POST', '/proposition',
			{variables: {login: playerName, idGame: gameName, proposition: JSON.stringify(proposition)},
				onload: function()
				{
					answer = (JSON.parse(this.responseText));
					reponseSelection(answer);
				}
			}
	);
}

//en gere la reponse de selection d'un robot selon ce que le serveur renvoi
function reponseSelection(answer) {
    if (answer.state == "INCOMPLETE") {
        if (answer.nextPositions) {
            rafrechirCouleurBordure();         
        }
    }
    else if (answer.state == "INVALID_SELECT") {
		x = propositions.pop();
		IdRobot = IdRobotPrec;
		afficherPropositionSansSelection(IdRobot)
		alert("Vous ne pouvez pas redéplacer un robot après en avoir déplacer un autre ");
		
    }
    else if (answer.state == "SUCCESS") {
        alert("buildSelectAnswer" + " : SUCCESS !");
    }
    else {
		alert(answer.state);
    }
}

//envoi d'une propostiion de mouvement au serveur avec Xmlhttprequest
function propositionMouvement(propozition) {
	var destLine = propozition[propozition.length - 1].line;
	var destCol = propozition[propozition.length - 1].column;
	var propXHR = XHR('POST', '/proposition',
			{variables: {login: playerName, idGame: gameName, proposition: JSON.stringify(propozition)},
				onload: function()
				{
					answer = (JSON.parse(this.responseText));
					reponseMouvement(answer, destLine, destCol);
				}
			}
	);
}

//en gere la reponse de mouvement d'un robot selon ce que le serveur renvoi
function reponseMouvement(answer, destLine, destColumn) {
	if (answer.state == "INCOMPLETE") {
		majPositionRobot(selectedRobot.line, selectedRobot.column, destLine, destColumn);
		initBordure();
		rafrechirCouleurBordure();
		placerRobot();
		dessinerCible(bord);
		
		//calcul du nombre d'opération en parcourant le tableau des propositions et en comptant le nombre de "move"
		for(var i=0;i<propositions.length;i++) 
		{
			if (propositions[i].command == "move")
			{
				nombreOperations++;
			}
		}
		document.getElementById("nboperations").innerHTML = nombreOperations;
		nombreOperations = 0;
	}
	if (answer.state == "SUCCESS") {
		majPositionRobot(selectedRobot.line, selectedRobot.column, destLine, destColumn);
		initBordure();
		rafrechirCouleurBordure();
		placerRobot();
		dessinerCible(bord);
		minutes = document.getElementById("minutes").innerHTML;
		secondes = document.getElementById("seconds").innerHTML;
		arretTempsDeJeu();
	}
	 if (answer.nextPositions) {
		 var propRobots=document.getElementsByClassName('robotprop');
		 //on enleve les prposition affiché sur le plateau de jeu
		var count=propRobots.length;
		for(var i=0;i<count;i++) 
		{
		propRobots[0].remove();
		}
		//on enleve les fleches de proposition
		var carreRobots=document.getElementsByClassName('robotcarre');
		count=carreRobots.length;
		for(var i=0;i<count;i++) 
		{
		carreRobots[0].remove();
		}
		var pathRobots=document.getElementsByClassName('paths');
		 count=pathRobots.length;
		for(var i=0;i<count;i++) 
		{
		pathRobots[0].setAttribute("class","");
		}
		//affichage de la proposition suivante apres un deplacement
var cd=0,cf=0,ld=0,lf=0;

		for (var i = 0; i < answer.nextPositions.length; i++) {
			if (!document.getElementById(answer.nextPositions[i].l + "_" + answer.nextPositions[i].c).innerHTML)
			{
				var id=answer.nextPositions[i].l +"_"+answer.nextPositions[i].c;
				document.getElementById(answer.nextPositions[i].l +"_"+answer.nextPositions[i].c).innerHTML = "<img class=\"robotprop\" id=\"" + Robots[IdRobot].id+ "\" src='style/img/" +Robots[IdRobot].color + "_robot.png' height='26px' width='22px' onclick=\"amenerRobot('"+id+"');\"/>";
				
			}
			//deplacement a gauche
			if (Robots[IdRobot].column > answer.nextPositions[i].c)
			{
				for (var j = (Robots[IdRobot].column-1); j >=0; j--) {
				if (bord.board[Robots[IdRobot].line][j].g) {
					break;
				}
				else {
					if (bord.board[Robots[IdRobot].line][j - 1].d) {
						break;
					}
					else if (robotDansLaPosition(Robots[IdRobot].line, (j - 1))) {
						break;
					}
				}
				document.getElementById(Robots[IdRobot].line + "_" + (j)).innerHTML = "<img class=\"robotcarre\" id=\"" + Robots[IdRobot].id+ "\" src='style/img/" +Robots[IdRobot].color + "_arrow_left.png' height='18px' width='18px' />";
				}
			}
			//deplacement a droite
			if (Robots[IdRobot].column < answer.nextPositions[i].c)
			{
				for (var j = (Robots[IdRobot].column+1); j < 16; j++) {
				if (bord.board[Robots[IdRobot].line][j].d) {
					break;
				}
				else {
					if (bord.board[Robots[IdRobot].line][j + 1].g) {
						break;
					}
					else if (robotDansLaPosition(Robots[IdRobot].line, (j + 1))) {
						break;
					}
				}
				document.getElementById(Robots[IdRobot].line + "_" + (j)).innerHTML = "<img class=\"robotcarre\" id=\"" + Robots[IdRobot].id+ "\" src='style/img/" +Robots[IdRobot].color + "_arrow_right.png' height='18px' width='18px' />";
			}
			}
			//deplacement haut
			if (Robots[IdRobot].line > answer.nextPositions[i].l)
			{
			for (var j = (Robots[IdRobot].line-1); j >=0; j--) {
				if (bord.board[j][Robots[IdRobot].column].h) {
					break;
				}
				else {
					if (bord.board[j - 1][Robots[IdRobot].column].b) {
						break;
					}
					else if (robotDansLaPosition((j-1), Robots[IdRobot].column)) {
						break;
					}
				}
				document.getElementById((j) + "_" + Robots[IdRobot].column).innerHTML = "<img class=\"robotcarre\" id=\"" + Robots[IdRobot].id+ "\" src='style/img/" +Robots[IdRobot].color + "_arrow_top.png' height='18px' width='18px' />";
				}
			}
			//deplacement a bas
			if (Robots[IdRobot].line < answer.nextPositions[i].l)
			{
				for (var j = (Robots[IdRobot].line+1); j <16; j++) {
				if (bord.board[j][Robots[IdRobot].column].b) {
					break;
				}
				else {
					if (bord.board[j + 1][Robots[IdRobot].column].h) {
						break;
					}
					else if (robotDansLaPosition((j+1), Robots[IdRobot].column)) {
						break;
					}
				}
				document.getElementById((j) + "_" + Robots[IdRobot].column).innerHTML = "<img class=\"robotcarre\" id=\"" + Robots[IdRobot].id+ "\" src='style/img/" +Robots[IdRobot].color + "_arrow_down.png' height='18px' width='18px' />";
				}
			}
		}
		
	}
	}
	
//bouger a droite
function mouvementVersLaDroite(ligne, c) {
	var id;
	for (var i = parseInt(c); i < 16; i++) {
		if (bord.board[ligne][i].d) {
			id = ligne + "_" + i;
			break;
		}
		else {
			if (bord.board[ligne][i + 1].g) {
				id = ligne + "_" + (i);
				break;
			}
			else if (robotDansLaPosition(ligne, (i + 1))) {
				id = ligne + "_" + (i);
				break;
			}
		}
	}
	return id;
}

//bouger a gauche
function mouvementVersLaGauche(ligne, colonne) {

	var id;
	for (var i = parseInt(colonne); i >=0; i--) {
		if (bord.board[ligne][i].g) {
			id = ligne + "_" + i;
			break;
		}
		else {
			if (bord.board[ligne][i - 1].d) {
				id = ligne + "_" + (i);
				break;
			}
			else if (robotDansLaPosition(ligne, (i - 1))) {
				id = ligne + "_" + (i);
				break;
			}
		}
	}
	return id;
}

//bouger en haut
function mouvementVersLeHaut(ligne, colonne) {
	var id;
	for (var i = parseInt(ligne); i >=0; i--) {
		if (bord.board[i][colonne].h) {
			id = i + "_" + colonne;
			break;
		}
		else {
			if (bord.board[i - 1][colonne].b) {
				id = i + "_" + colonne;
				break;
			}
			else if (robotDansLaPosition((i-1), colonne)) {
				id = i + "_" + colonne;
				break;
			}
		}
	}
	return id;
}

//bouger en bas
function mouvementVersLeBas(ligne, colonne) {
	var id;
	for (var i = parseInt(ligne); i <16; i++) {
		if (bord.board[i][colonne].b) {
			id = i + "_" + colonne;
			break;
		}
		else {
			if (bord.board[i + 1][colonne].h) {
				id = i + "_" + colonne;
				break;
			}
			else if (robotDansLaPosition((i+1), colonne)) {
				id = i + "_" + colonne;
				break;
			}
		}
	}
	return id;
}

//verifier s'il y a un robot sur la cellule (ligne l ,colonne c)
function robotDansLaPosition(ligne, colonne) {
	res = false;
	for (var i = 0; i < 4; i++) {
		if (Robots[i].line == ligne && Robots[i].column == colonne)
			res = true;
	}
	return res;
}
	
function testerEtatDuJeu(val) {
	if (val != "") {
		alert("cette partie terminé");
		document.forms["backToLogin"].submit();
	}
}




